/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React, { useState } from 'react';
import { Button, Form, Input, message } from 'antd';
import styles from './index.module.css';
import {ResetPassword} from "../../../api/AccountApi";
import {jump} from "../../../libs/funcs";
import {logout} from "../../../libs/storage";


export default function Reset(props) {
  const [loading, setLoading] = useState(false);
  const [oldPassword, setOldPassword] = useState();
  const [newPassword, setNewPassword] = useState();
  const [newPasswordAgain, setNewPasswordAgain] = useState();

  function handleSubmit() {

    if (!oldPassword) {
      message.error('请输入原密码')
      return
    } else if (!newPassword) {
      message.error('请输入新密码')
      return
    }else if (oldPassword === newPassword){
      message.error('新密码不能跟旧密码相同')
      return
    } else if (newPassword !== newPasswordAgain) {
      message.error('两次输入密码不一致')
      return
    }

    setLoading(true);
    let data = {
      "oldPassword":oldPassword,
      "newPassword":newPassword,
      "newPasswordAgain":newPasswordAgain
    };
    ResetPassword(data).then(response => {
      if (response.data.code === 200){
        message.success(response.data.msg);
        logout();
        jump("/");
      }
    }).finally(() => setLoading(false));
  }

  return (
    <React.Fragment>
      <div className={styles.title}>修改密码</div>
      <Form style={{maxWidth: 320}} labelCol={{span: 6}} wrapperCol={{span: 18}}>
        <Form.Item label="原密码">
          <Input.Password value={oldPassword} placeholder="请输入" onChange={e => setOldPassword(e.target.value)}/>
        </Form.Item>
        <Form.Item label="新密码">
          <Input.Password value={newPassword} placeholder="请输入" onChange={e => setNewPassword(e.target.value)}/>
        </Form.Item>
        <Form.Item label="再次确认">
          <Input.Password value={newPasswordAgain} placeholder="请输入" onChange={e => setNewPasswordAgain(e.target.value)}/>
        </Form.Item>
        <Form.Item>
          <Button type="primary" loading={loading} onClick={handleSubmit}>保存设置</Button>
        </Form.Item>
      </Form>
    </React.Fragment>
  )
}
